package com.sonicvision.resourcetracker.employee;

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.sonicvision.resourcetracker.exceptions.ServiceException;

@Controller
public class EmployeeController {

	@Autowired
	private EmployeeService empService;

	@RequestMapping(value = "/addemployee", method = RequestMethod.GET)
	public ModelAndView addEmployee() {
		System.out.println("I am inside get");
		ModelAndView modelAndView = new ModelAndView();
		Employee employee = new Employee();
		modelAndView.addObject("employee", employee);
		modelAndView.setViewName("AddEmployee");

		return modelAndView;
	}

	@RequestMapping(value = "/addemployee", method = RequestMethod.POST)
	public ModelAndView addEmployee(@Valid Employee employee, BindingResult br) {

		System.out.println("I am inside post");

		ModelAndView modelAndView = new ModelAndView();

		try {
			if (br.hasErrors()) {
				System.out.println("i am inside if");
				modelAndView.addObject("employee", employee);
				modelAndView.setViewName("AddEmployee");
				return modelAndView;
			} else {
				System.out.println("i am inside else");
				empService.addEmployee(employee);
				modelAndView.addObject("employee", employee);
				modelAndView.setViewName("Acknowledge");
				return modelAndView;

			}
		} catch (ServiceException e) {
			System.out.println("i am inside catch");
			e.printStackTrace();
			return null;
		}

	}

}
